<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPermission(1,'0')">添加权限</el-button>
        </div>

        <el-table :data="permissionList" row-key="id" border>
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="code" label="标识" />
          <el-table-column prop="description" label="描述" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button v-if="scope.row.type===1" type="text" @click="addPermission(2,scope.row.id)">添加</el-button>
              <el-button type="text" @click="editPermission(scope.row.id)">编辑</el-button>
              <el-button v-if="!scope.row.children" type="text" @click="delPermission(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 放置一个弹层 用来编辑新增节点 -->
        <el-dialog title="新增权限点" :visible="showDialog" @close="btnCancel">
          <!-- 表单 -->
          <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限描述">
              <el-input v-model="formData.description" style="width:90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" type="primary" @click="addOrEditSubmit">确定</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
// 接口
import { getPermissionListAPI, addPermissionAPI, getPermissionDetailAPI, updatePermissionAPI, delPermissionAPI } from '@/api/permission'
// 转树形结构的方法
import { transTreeD } from '@/utils'
export default {
  name: 'Permission',
  data() {
    const validName = (rules, value, callback) => {
      // 添加=>同级的名字不能相同
      let existNameList = this.originList.filter(item => item.pid === this.formData.pid)

      // 编辑=>如果是编辑,排除自己的名字,name能取自己
      if (this.isEdit) {
        existNameList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      // 验证,形成一个name的数组,是否报包含这个值
      existNameList.map(item => item.name).includes(value) ? callback(new Error(value + '已存在')) : callback()
    }

    const validCode = (rules, value, callback) => {
      // 添加=>所有的code不能相同
      let existCodeList = this.originList

      // 编辑=>如果是编辑,排除自己的名字,code能取自己
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.formData.id)
      }
      // 验证,形成一个code的数组,是否报包含这个值
      existCodeList.map(item => item.code).includes(value) ? callback(new Error(value + '已存在')) : callback()
    }
    return {
      permissionList: [], // 权限管理列表数据
      showDialog: false, // 是否显示弹层
      // 添加权限
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      // 添加权限的规则
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [{ required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }]
      },
      isEdit: false, // 是否是编辑,
      originList: [] // 做校验时用到的数据
    }
  },
  created() {
    // 调用获取权限列表的方法
    this.getPermissionListFn()
  },
  methods: {

    // 删除权限
    async delPermission(id) {
      const res = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (res === 'cancel') return this.$message('您取消了删除')
      await delPermissionAPI(id)
      this.getPermissionListFn()
    },

    // 添加权限按钮
    addPermission(type, pid) {
      this.isEdit = false
      this.formData.type = type
      this.formData.pid = pid
      this.showDialog = true
    },

    // 编辑选前按钮
    async editPermission(id) {
      this.isEdit = true
      this.showDialog = true
      const res = await getPermissionDetailAPI(id)
      this.formData = res.data
    },

    // 添加权限方法
    async addPermissionFn() {
      await addPermissionAPI(this.formData)
    },

    // 编辑权限方法
    async editPermissionFn() {
      await updatePermissionAPI(this.formData)
    },

    // 添加/编辑权限确定按钮
    addOrEditSubmit() {
      this.$refs.perForm.validate(async valid => {
        if (!valid) return
        this.isEdit ? await this.editPermissionFn() : await this.addPermissionFn()
        this.getPermissionListFn()
        this.showDialog = false
        this.isEdit = false
      })
    },

    // 添加/变价权限取消按钮
    btnCancel() {
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      this.$refs.perForm.resetFields()
      this.isEdit = false
      this.showDialog = false
    },

    // 获取权限列表的方法
    async getPermissionListFn() {
      const res = await getPermissionListAPI()
      this.originList = res.data.map(({ id, name, pid, code }) => ({ id, name, pid, code }))
      this.permissionList = transTreeD(res.data, '0')
    }
  }
}
</script>

<style lang="scss" scoped></style>
